package net.dgg.zz.credential.guidePriceConfigure.controller;

import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.framework.tac.utils.web.commmon.DggBaseController;
import net.dgg.iboss.base.util.datatable.DataTableUtils;
import net.dgg.iboss.base.util.datatable.domain.DataTableRequest;
import net.dgg.tmd.foundation.platform.annotation.AuthOpt;
import net.dgg.tmd.foundation.platform.org.entity.OrganizationDTO;
import net.dgg.tmd.foundation.platform.org.service.OrganizationManager;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.zz.common.constant.CredentialConstant;
import net.dgg.zz.common.excption.CommonExcption;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.DataTableResponse;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.excel.ExcelUtils;
import net.dgg.zz.credential.excption.CertificateExcption;
import net.dgg.zz.credential.guidePriceConfigure.dto.GuidePriceDto;
import net.dgg.zz.credential.guidePriceConfigure.service.GuidePriceConfigService;
import net.dgg.zz.credential.guidePriceConfigure.vo.GuidePriceVo;
import net.fblock.log.NLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author zsx
 * @Title: GuidePriceConfigController
 * @ProjectName zzsc
 * @Description: 证书指导价配置
 * @date 2018/8/17 11:00
 */
@Controller
@RequestMapping("/zs/guide_price_config")
public class GuidePriceConfigController extends DggBaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private GuidePriceConfigService guidePriceConfigService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private OrganizationManager organizationManager;
    @Autowired
    private SystemRecordService systemRecordService;

    /*
     * @Author zsx
     * @Date 2018-08-17 02:08:58
     * @Description 初始化页面
     * @return String
     */
    @AuthOpt(code = "ZS_GUIDE_PRICE_CONFIG")
    @RequestMapping("/index")
    public String index(Model model) {
        // 适用范围
        List<Map> applicationScopes = commonService.queryTreeBook(CredentialConstant.CREDENTIAL_APPLICATION_SCOPE, 1, 2, null);
        model.addAttribute("applicationScopes", applicationScopes);
        model.addAttribute("GENERAL_CREDENTIAL", CredentialConstant.GENERAL_CREDENTIAL);
        return "zzsc/guidePriceConfig/index";
    }

    /*
     * @Author zsx
     * @Date 2018-08-17 05:08:11
     * @Description 分页获取数据
     * @param params
     * @return DggRestResponse
     */
    @RequestMapping("/query_guide_price_list")
    @ResponseBody
    @NLog
    public DataTableResponse queryGuidePriceList(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        DataTableRequest dt = DataTableUtils.getParam(request);
        params.put("page", dt.getPage());
        params.put("limit", dt.getLength());
        List<GuidePriceVo> list = guidePriceConfigService.queryGuidePriceWithPage(params);
        return new DataTableResponse().data(params, list);
    }


    /*
     * @Author zsx
     * @Date 2018-08-17 02:08:20
     * @Description 添加指导价配置
     * @param params
     * @return DggRestResponse
     */
    @RequestMapping("/add_guide_price")
    @ResponseBody
    @NLog
    public DggRestResponse addGuidePrice(GuidePriceDto priceDto) {
        try {
            if (null != priceDto.getIsAll() && priceDto.getIsAll().equals("0")) {
                OrganizationDTO organ = organizationManager.findOrgParentByLevel(sessionManager.getCurrentUser().getOrgId(), "ORG_LEVEL_1");
                priceDto.setSignOrgId(organ.getId());
                priceDto.setSignOrgName(organ.getName());
            }
            if (StringUtils.isEmpty(priceDto.getSignOrgId())) {
                return this.getFailResponse("事业部id不能为空");
            }
            if (StringUtils.isEmpty(priceDto.getCertificateTypeId())) {
                return this.getFailResponse("证书类型不能为空");
            }
            if (StringUtils.isEmpty(priceDto.getCertificateMajorId())) {
                return this.getFailResponse("证书专业不能为空");
            }
            if (StringUtils.isEmpty(priceDto.getCertificateLevel())) {
                return this.getFailResponse("证书等级不能为空");
            }
            if (StringUtils.isEmpty(priceDto.getCertificateArea())) {
                return this.getFailResponse("地区不能为空");
            }
            if (StringUtils.isEmpty(priceDto.getApplicationScope())) {
                return this.getFailResponse("适用范围不能为空");
            }
            if (StringUtils.isEmpty(priceDto.getCertificateGuidingPrice())) {
                return this.getFailResponse("指导价不能为空");
            }
            Map<String, Object> map = guidePriceConfigService.addGuidePrice(priceDto);
            if ((Boolean) map.get("status")) {
                return this.getSuccessResponse("");
            } else {
                return this.getFailResponse(map.get("msg").toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse("服务器错误,请联系管理员");
        }
    }

    /*
     * @Author zsx
     * @Date 2018-08-21 11:08:32
     * @Description
     * @param id 配置id
     * @param certificateGuidingPrice 收证指导价
     * @param hang_up_guiding_price 使用指导价格
     * @return DggRestResponse
     */
    @RequestMapping("/update_guide_price")
    @ResponseBody
    @NLog
    public DggRestResponse updateGuidePrice(Long id, BigDecimal certificateGuidingPrice, BigDecimal hangUpGuidingPrice) {
        try {
            if (StringUtils.isEmpty(certificateGuidingPrice)) {
                return this.getFailResponse("证书指导价不能为空");
            }
            if (StringUtils.isEmpty(hangUpGuidingPrice)) {
                return this.getFailResponse("使用指导价不能为空");
            }
            Map<String, Object> map = guidePriceConfigService.updateGuidePrice(id, certificateGuidingPrice, hangUpGuidingPrice, -1);
            if ((Boolean) map.get("status")) {
                return this.getSuccessResponse("");
            } else {
                return this.getFailResponse(map.get("msg").toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return getFailResponse("服务器错误，请联系管理员");
        }
    }

    /*
     * @Author zsx
     * @Date 2018-08-21 12:08:36
     * @Description 修改启用状态
     * @param id
     * @param type 0启用 1停用
     * @return DggRestResponse
     */
    @RequestMapping("/update_status")
    @ResponseBody
    @NLog
    public DggRestResponse updateStatus(Long guidePriceId, Integer type) {
        try {
            Map<String, Object> map = guidePriceConfigService.updateGuidePrice(guidePriceId, BigDecimal.ZERO, BigDecimal.ZERO, type);
            if ((Boolean) map.get("status")) {
                return this.getSuccessResponse("");
            } else {
                return this.getFailResponse(map.get("msg").toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse("服务器错误，请联系管理员");
        }
    }

    /*
     * @Author zsx
     * @Date 2018-08-21 07:08:27
     * @Description 根据事业部id查询当月是否存在数据
     * @param null
     * @return null
     */
    @RequestMapping("/check_guide_pricec")
    @ResponseBody
    @NLog
    public DggRestResponse checkGuidePrice(Long signOrgId) {
        Integer cont = guidePriceConfigService.selectGuidPriceCount(signOrgId);
        if (cont > 0) {
            return this.getFailResponse("本月已存在数据，一但确定复制指导价将永久删除本月已存在数据，确定要复制?");
        }
        return this.getSuccessResponse("");
    }

    /*
     * @Author zsx
     * @Date 2018-08-21 06:08:43
     * @Description 复制指导价
     * @param signOrgId 事业部id
     * @param month 年月
     * @return DggRestResponse
     */
    @RequestMapping("/copy_guide_price")
    @ResponseBody
    @NLog
    public DggRestResponse copyGuidePrice(Long signOrgId, String month, String isAll) {
        if (isAll.equals("0")) {
            signOrgId = commonService.findUserSyb(sessionManager.getCurrentUser());
        }
        if (null == signOrgId) {
            return this.getFailResponse("事业部不能为空");
        }
        if (StringUtils.isEmpty(month)) {
            return this.getFailResponse("日期不能为空");
        }
        try {
            Map<String, Object> map = guidePriceConfigService.copyGuidePrice(signOrgId, month);
            if ((Boolean) map.get("status")) {
                return this.getSuccessResponse("");
            } else {
                return this.getFailResponse(map.get("msg").toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse("服务器错误，请联系管理员");
        }
    }

    /**
     * 查询证书专业的指导价
     *
     * @return
     */
    @NLog()
    @RequestMapping("/count_guide_price")
    @ResponseBody
    public DggRestResponse countGuidePrice(@RequestParam Map params) {
        try {
            Map map = guidePriceConfigService.countGuidePrice(params);
            return this.getSuccessResponse(map);
        } catch (CertificateExcption e) {
            return this.getFailResponse(e.getMessage());
        } catch (CommonExcption e) {
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
            return this.getFailResponse(e.getMessage());
        }
    }

    /*
     * @Author zsx
     * @Date 2018-08-22 12:08:20
     * @Description 导出指导价
     */
    @RequestMapping(value = "/export_guide_price")
    @ResponseBody
    @NLog()
    public void exportGuidePrice(@RequestParam Map params, HttpServletRequest request, HttpServletResponse response) {
        try {
            params.put("start", null);
            params.put("limit", null);
            List<GuidePriceVo> list = guidePriceConfigService.queryGuidePriceWithPage(params);
            String fileName = "证书指导价配置" + DateUtils.dateString(new Date(), DateUtils.yyyy_MM_dd_HH_mm_ss) + ".xlsx";
            ExcelUtils.writeToFile(list, null, fileName, response,GuidePriceVo.class);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            SystemRecord record = new SystemRecord();
            record.setSource("1");
            record.setOperateType("53");
            record.setWorkTableName("zz_warning_configure");
            record.setRemarks("导出指导价");
            systemRecordService.save(record);
        }

    }
}
